package com.tanhua.dubbo.async;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 第二步：异步处理类：异步将 循环遍历好友数据，往好友时间线表插入数据
 */
@Component
@Slf4j
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 往好友时间线表插入数据
     */
    @Async
    public void saveTimeLine(Long nowTime, Long userId, ObjectId movementId){
        log.debug("****开始**saveTimeLine******************");
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3.循环遍历好友数据，往好友时间线表插入数据
        if(!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movementId);//直接从保存动态对象中获取即可
                movementTimeLine.setUserId(userId);//发布动态的用户id
                movementTimeLine.setFriendId(friend.getFriendId());//好友id
                movementTimeLine.setCreated(nowTime);//时间
                mongoTemplate.insert(movementTimeLine);
            }
        }
        log.debug("***结束***saveTimeLine*********成功了******");
    }
}
